import { useHead } from "@vueuse/head";
import {
  getSeoConfig,
  getArticleStructuredData,
  getWebsiteStructuredData,
  type SeoConfig
} from "@/api/seo";

/**
 * SEO工具类
 * 用于管理网站的SEO配置和结构化数据
 */
export class SeoUtil {
  /** 全局SEO配置 */
  static seoConfig: SeoConfig | null = null;

  /**
   * 初始化SEO配置(在App.vue中调用一次)
   */
  static async init(): Promise<SeoConfig | null> {
    try {
      const response = await getSeoConfig();
      this.seoConfig = response.data || null;
      console.log("✅ SEO配置初始化成功:", this.seoConfig);
      return this.seoConfig;
    } catch (error) {
      console.error("❌ 获取SEO配置失败:", error);
      return null;
    }
  }

  /**
   * 设置页面SEO(在每个页面组件中调用)
   * @param options - SEO选项
   * @param options.title - 页面标题
   * @param options.description - 页面描述
   * @param options.keywords - 页面关键词
   * @param options.image - 页面图片
   * @param options.type - 页面类型(website/article)
   * @param options.structuredData - 结构化数据JSON字符串
   * @param options.author - 文章作者(仅article类型使用)
   * @param options.publishTime - 发布时间(仅article类型使用)
   * @param options.updateTime - 更新时间(仅article类型使用)
   */
  static setPageSeo(
    options: {
      title?: string;
      description?: string;
      keywords?: string;
      image?: string;
      type?: "website" | "article";
      structuredData?: string;
      author?: string;
      publishTime?: string;
      updateTime?: string;
    } = {}
  ) {
    if (!this.seoConfig) {
      console.warn("⚠️ SEO配置未初始化，请先调用 SeoUtil.init()");
      return;
    }

    const {
      title = this.seoConfig.siteName,
      description = this.seoConfig.siteDescription,
      keywords = this.seoConfig.siteKeywords,
      image = this.seoConfig.siteLogo,
      type = "website",
      structuredData = null,
      author = this.seoConfig.siteAuthor,
      publishTime,
      updateTime
    } = options;

    // 构建完整标题
    const fullTitle =
      title === this.seoConfig.siteName
        ? title
        : `${title} - ${this.seoConfig.siteName}`;

    // 构建基础head配置
    const headConfig: any = {
      title: fullTitle,
      meta: [
        // 基础SEO
        { name: "description", content: description },
        { name: "keywords", content: keywords },
        { name: "author", content: author },
        { name: "robots", content: this.seoConfig.robotsMetaContent },

        // Open Graph
        { property: "og:type", content: type },
        { property: "og:title", content: title },
        { property: "og:description", content: description },
        { property: "og:image", content: this.formatImageUrl(image) },
        { property: "og:url", content: window.location.href },
        { property: "og:site_name", content: this.seoConfig.siteName }
      ],
      link: [
        { rel: "icon", href: this.seoConfig.siteFavicon },
        { rel: "canonical", href: window.location.href }
      ]
    };

    // 如果是文章类型,添加额外的meta标签
    if (type === "article") {
      if (publishTime) {
        headConfig.meta.push({
          property: "article:published_time",
          content: publishTime
        });
      }
      if (updateTime) {
        headConfig.meta.push({
          property: "article:modified_time",
          content: updateTime
        });
      }
      if (author) {
        headConfig.meta.push({
          property: "article:author",
          content: author
        });
      }
    }

    // 添加Twitter Card(如果启用)
    if (this.seoConfig.twitterCardEnabled) {
      headConfig.meta.push(
        { name: "twitter:card", content: this.seoConfig.twitterCardType },
        { name: "twitter:site", content: this.seoConfig.twitterSite },
        { name: "twitter:title", content: title },
        { name: "twitter:description", content: description },
        { name: "twitter:image", content: this.formatImageUrl(image) }
      );
    }

    // 添加结构化数据
    if (structuredData) {
      headConfig.script = [
        {
          type: "application/ld+json",
          children: structuredData
        }
      ];
    }

    // 使用@vueuse/head设置页面head
    useHead(headConfig);

    console.log("📄 页面SEO已设置:", { title: fullTitle, type });
  }

  /**
   * 获取文章结构化数据
   * @param articleId - 文章ID
   */
  static async getArticleStructuredData(
    articleId: number
  ): Promise<string | null> {
    try {
      const response = await getArticleStructuredData(articleId);
      return response.data || null;
    } catch (error) {
      console.error("❌ 获取文章结构化数据失败:", error);
      return null;
    }
  }

  /**
   * 获取网站结构化数据
   */
  static async getWebsiteStructuredData(): Promise<string | null> {
    try {
      const response = await getWebsiteStructuredData();
      return response.data || null;
    } catch (error) {
      console.error("❌ 获取网站结构化数据失败:", error);
      return null;
    }
  }

  /**
   * 格式化图片URL为完整URL
   * @param imageUrl - 图片URL
   */
  private static formatImageUrl(imageUrl: string): string {
    if (!imageUrl) return "";

    // 如果已经是完整URL,直接返回
    if (imageUrl.startsWith("http://") || imageUrl.startsWith("https://")) {
      return imageUrl;
    }

    // 如果是相对路径,拼接当前域名
    const origin = window.location.origin;
    return imageUrl.startsWith("/")
      ? `${origin}${imageUrl}`
      : `${origin}/${imageUrl}`;
  }

  /**
   * 清除页面SEO(用于页面卸载时清理)
   */
  static clearPageSeo() {
    if (!this.seoConfig) return;

    // 恢复为默认配置
    this.setPageSeo({
      title: this.seoConfig.siteName,
      description: this.seoConfig.siteDescription,
      keywords: this.seoConfig.siteKeywords,
      image: this.seoConfig.siteLogo,
      type: "website"
    });
  }
}
